<!doctype html>
<html lang='en' xmlns:th='http://www.thymeleaf.org'>
    <head th:replace="~{commons/common::dom-head('新增帖子')}">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css"/>
        <!-- 图标 -->
        <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.13.0/css/all.css">
        <!-- UIkit CSS -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.2.2/dist/css/uikit.min.css"/>
        <!-- 自定义 CSS -->
        <link rel="stylesheet" th:href="@{/static/css/common.css}" href="../../../static/css/common.css">
        <title>新增帖子</title>
    </head>
    <style>
        .edit input, .edit textarea {
            padding: 10px;
            font-size: 13px;
            color: #333;
        }

        .edit textarea {
            border-radius: 0;
            box-sizing: border-box;
            width: 100%;
            height: 200px;
            padding: 6px;
            line-height: 150%;
            tab-size: 3;
        }

        /* 附件图片 */
        .thumb-box {
            display: inline-block;
            margin: 10px 10px 10px 0;
            position: relative;
            border: 1px dotted #ccc;
            border-radius: 4px;
            width: 150px;
            height: 100px;
            background-color: #fcfcfc;
        }

        .thumb-box .thumb {
            position: absolute;
            left: 50%;
            top: 50%;
            max-width: 90%;
            max-height: 90%;
            transform: translateX(-50%) translateY(-50%);
            cursor: pointer;
        }

        .thumb-box .delete {
            position: absolute;
            right: 1px;
            top: 1px;
            background-color: #f1f1e3;
        }

        .thumb-box .delete:hover {
            background-color: #e1e1e8;
        }
    </style>
    <body>
        <div class="header bg-light mb-3 shadow-sm" th:replace="~{commons/common::navbar(2)}">
            <nav class="navbar navbar-expand-lg navbar-light bg-light container">
                <a th:href="@{/}" class="navbar-brand" href="#">我的论坛</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse"
                        data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav mr-auto">
                        <li class="nav-item">
                            <a th:href="@{/}" class="nav-link" href="#">首页 <span
                                    class="sr-only">(current)</span></a>
                        </li>
                        <li class="nav-item" th:if="${session.USER != null}">
                            <a class="nav-link" href="#" th:href="@{/u/message/add}">新增</a>
                        </li>
                    </ul>
                    <a th:if="${session.USER == null}" th:href="@{/login}"
                       class="text-decoration-none text-primary">请登录</a>
                    <div class="nav-item dropdown" th:if="${session.USER != null}">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button"
                           data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fas fa-user"></i>
                            <span class="text-primary" th:text="${session.USER.name}">用户名</span>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                            <a class="dropdown-item" href="#">个人中心</a>
                            <button id="logoutBtn" class="dropdown-item"><i class="fas fa-power-off"></i> 注销</button>
                        </div>
                    </div>
                </div>
            </nav>
        </div>

        <div class="content">
            <!-- 返回版面 -->
            <div class="card container">
                <div class="card-body">
                    <a th:href="@{/}" class="text-primary"><i class="far fa-hand-point-left"></i> 返回版面</a>
                </div>
            </div>
            <div class="container p-5 border text-dark bg-white">
                <div class="row-cols-1">
                    <h3 class="text-primary text-center header">帖子内容</h3>
                </div>
                <div class="row-cols-1 edit">
                    <div class="form-group">
                        <input type='text' id="title" class='form-control' placeholder='标题可免'>
                        <textarea id="content" class='form-control' placeholder='内容10字以上'></textarea>
                    </div>
                </div>
                <div class="clearfix">
                    <div class="col-md-12">
                        <div class="img-list">
                            <input id="fileSelector" type="file" style="display: none" onchange="selectFile(this)">
                            <div class="text-muted font-weight-bold">
                                上传附件图片(最多三张，每张不得超过1MB)
                            </div>
                            <div class="thumb-box">
                                <img th:src="@{/static/img/imageup.png}" src="../../../static/img/imageup.png"
                                     class="thumb img-thumbnail" alt="thumb" onclick="thumbClick(this)">
                                <i class="fas fa-window-close delete" onclick="thumbDelete(this)"></i>
                            </div>
                            <div class="thumb-box">
                                <img th:src="@{/static/img/imageup.png}" src="../../../static/img/imageup.png"
                                     class="thumb img-thumbnail" alt="thumb" onclick="thumbClick(this)">
                                <i class="fas fa-window-close delete" onclick="thumbDelete(this)"></i>
                            </div>
                            <div class="thumb-box">
                                <img th:src="@{/static/img/imageup.png}" src="../../../static/img/imageup.png"
                                     class="thumb img-thumbnail" alt="thumb" onclick="thumbClick(this)">
                                <i class="fas fa-window-close delete" onclick="thumbDelete(this)"></i>
                            </div>
                        </div>
                    </div>
                    <div class="float-right">
                        <a id="backBtn" class="btn btn-light mx-1" style="width: 70px" onClick="history.back(-1)">返回</a>
                        <button id="saveBtn" class="btn btn-primary mx-1" style="width: 70px">发布</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer" th:replace="~{commons/common::footer}">
            <hr>
            <div class="text-center">
                <p class="small text-muted m-0">
                    <span id="span"></span> | All Right Reserved © 2020 Designed by AJun
                </p>
                <a class="text-decoration-none text-muted small m-0" target="_blank"
                   href="http://www.beian.miit.gov.cn/">
                    备案号: 陕ICP备19017955号
                </a>
            </div>
            <script type="text/javascript">
                function runtime() {
                    // 初始时间，日/月/年 时:分:秒
                    X = new Date("5/30/2020 12:28:00");
                    Y = new Date();
                    T = (Y.getTime() - X.getTime());
                    M = 24 * 60 * 60 * 1000;
                    a = T / M;
                    A = Math.floor(a);
                    b = (a - A) * 24;
                    B = Math.floor(b);
                    c = (b - B) * 60;
                    C = Math.floor((b - B) * 60);
                    D = Math.floor((c - C) * 60);
                    //信息写入到DIV中
                    span.innerHTML = "小站已勉强运行: " + A + "天" + B + "小时" + C + "分" + D + "秒"
                }

                setInterval(runtime, 1000);
            </script>
        </div>

        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src='https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js'></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js"></script>
        <script th:src="@{/static/js/bootstrapQ.js}" src="../../static/js/bootstrapQ.js"></script>
        <script th:inline="javascript">
            /* 用户注销 */
            $('#logoutBtn').click(function () {
                $.ajax({
                    url: /*[[@{/logout.do}]]*/'',
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    processData: false,
                    success: function (resp) {
                        if (resp.success) {
                            location.href = /*[[@{/}]]*/'';
                        }
                    },
                    error: function () {
                        bootstrapQ.msg({msg: '网络异常', type: 'danger', time: 2000});
                    }
                });
            })

            /* 保存帖子 */
            $('#saveBtn').click(function () {
                let content = $('#content');
                let req = {};
                req.title = $('#title').val();
                req.content = content.val();
                if (content.val().trim().length < 3) {
                    bootstrapQ.msg({msg: '需输入10字符以上', type: 'warning', time: 2000});
                    return;
                }
                if (req.title.length === 0) {
                    // 从正文里提取前30字作为标题
                    req.title = req.content.substring(0, 30);
                    req.title = req.title.replace(/\\n/g, ''); // 去掉\n的换行符
                }

                /* 附件图片 */
                let imgNames = new Array(3);
                let thumbList = $('.thumb');
                for (let i = 0; i < thumbList.length; i++) {
                    if (thumbList[i].data != null) {
                        imgNames[i] = thumbList[i].data.tmpName;
                    }
                }
                req.img1 = imgNames[0];
                req.img2 = imgNames[1];
                req.img3 = imgNames[2];

                $.ajax({
                    url: /*[[@{/u/message/add.do}]]*/'',
                    method: 'POST',
                    data: JSON.stringify(req),
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    processData: false,
                    success: function (resp) {
                        if (resp.success) {
                            location.href = /*[[@{/}]]*/''
                        } else {
                            bootstrapQ.msg({msg: resp.message, type: 'warning', time: 2000});
                        }
                    },
                    error: function () {
                        bootstrapQ.msg({msg: '网络异常', type: 'danger', time: 2000});
                    }
                });
            })

            /* 附件图片上传 */
            // 模拟点击
            function thumbClick(dom) {
                let fileSelector = $('#fileSelector');
                fileSelector.click(); // 模拟点击 file 控件
                fileSelector[0].target = dom; // dom指向 <img>控件
            }

            // 图片清除
            function thumbDelete(dom) {
                let thumb = $(dom).prev('.thumb'); // 找兄弟 dom 元素
                $(thumb).prop('src', /*[[@{/static/img/imageup.png}]]*/'');
                $(thumb).data = null;
            }

            // 图片上传
            function selectFile(btn) {
                // 获取选择的文件
                let file = btn.files[0]; // 获取用户选择的文件
                let formData = new FormData(); // 构造表单对象
                formData.append('file', file); // 添加文件表单项

                btn.value = ''; // 清除文件选择按钮的选择
                let thumb = btn.target; // <img> 控件

                // 文件后缀和大小检查
                let type = file.type;
                if (type !== 'image/jpeg' && type !== 'image/png') {
                    bootstrapQ.msg({msg: '不支持的类型' + type, type: 'warning', time: 2000});
                    return;
                }
                if (file.size > 3000000) {
                    bootstrapQ.msg({msg: '图片太大,不得大于3MB!', type: 'warning', time: 2000});
                    return;
                }

                /* 文件上传 */
                $.ajax({
                    url: /*[[@{/u/message/imgUpload.do}]]*/'',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (resp) {
                        if (resp.success) {
                            let data = resp.data;
                            $(thumb).prop('src', data.tmpUrl);
                            thumb.data = data; // 记录应答数据
                        } else {
                            bootstrapQ.msg({msg: resp.message, type: 'warning', time: 2000});
                        }
                    },
                    error: function () {
                        bootstrapQ.msg({msg: '网络异常', type: 'danger', time: 2000});
                    }
                });
            }
        </script>
    </body>
</html>